//
//  XGChatViewController.m
//  HuanXin
//
//  Created by monkey on 2019/7/8.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <Hyphenate/Hyphenate.h>

#import "XGChatViewController.h"
#import "XGConversationViewController.h"

#import "XGChatMessageModel.h"
#import "XGUserModel.h"

#import "XGChatTableViewCell.h"

static NSString *const kNormalTitle = @"环信";
static NSString *const kConnectingTitle = @"连接中...";
static NSString *const kReceivingTitle = @"接收中...";
static NSString *const kDisconnectedTitle = @"环信(未连接)";

static NSString *XGChatTableViewCellReuseIdentifier = @"XGChatTableViewCell";

/// 自定义会话对象排序方法
/// @param obj1 会话对象1
/// @param obj2 会话对象2
/// @param context context
NSInteger sortConversation(EMConversation *obj1,EMConversation *obj2,void *context)
{
    NSInteger time1 = obj1.latestMessage.localTime;
    NSInteger time2 = obj2.latestMessage.localTime;
    if (time2 > time1) {
        return NSOrderedDescending;
    } else if (time2 < time1) {
        return NSOrderedAscending;
    } else {
        return NSOrderedSame;
    }
}

@interface XGChatViewController () <EMClientDelegate,EMChatManagerDelegate>
{
    /// 所有会话
    NSMutableArray<EMConversation *> *_conversationArrM;
}

@end

@implementation XGChatViewController

#pragma mark - 控制器生命周期方法

- (void)viewDidLoad
{
    [super viewDidLoad];

    _conversationArrM = [NSMutableArray arrayWithCapacity:10];
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView registerClass:[XGChatTableViewCell class] forCellReuseIdentifier:XGChatTableViewCellReuseIdentifier];
    self.tableView.rowHeight = 64;
    
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self loadConversations];
}

- (void)dealloc
{
    [[EMClient sharedClient] removeDelegate:self];
    [[EMClient sharedClient].chatManager removeDelegate:self];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _conversationArrM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XGChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:XGChatTableViewCellReuseIdentifier];
    EMMessage *message = [_conversationArrM[indexPath.row] latestMessage];
    NSDate *date = [NSDate dateWithTimeIntervalInMilliSecondSince1970:message.localTime];
    XGChatMessageModel *messageModel = [XGChatMessageModel messageModelWithDate:date emmessage:message];
    int unreadCount = [_conversationArrM[indexPath.row] unreadMessagesCount];
    [cell setMessageModel:messageModel unreadCount:unreadCount];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XGConversationViewController *viewController = [XGConversationViewController conversationViewControllerWithUserName:_conversationArrM[indexPath.row].conversationId];
    NSInteger count = _conversationArrM[indexPath.row].unreadMessagesCount;
    viewController.markAllCompletion = ^(NSString *conversationId) {
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        NSInteger unreadCount = [self.tabBarItem.badgeValue integerValue];
        unreadCount -= count;
        [self setTabBarItemBageValue:unreadCount];
    };
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        EMConversation *conversation = _conversationArrM[indexPath.row];
        [[EMClient sharedClient].chatManager deleteConversation:conversation.conversationId isDeleteMessages:YES completion:^(NSString *aConversationId, EMError *aError) {
            if (aError) {
                DEBUG_Log(@"删除会话失败\n");
                return;
            }
            
            NSInteger unreadCount = self.tabBarItem.badgeValue.integerValue;
            unreadCount -= conversation.unreadMessagesCount;
            [self setTabBarItemBageValue:unreadCount];
            
            // 移除本地记录
            [self->_conversationArrM removeObject:conversation];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

#pragma mark - EMClientDelegate

// SDK连接服务器的状态变化时会接收到该回调
- (void)connectionStateDidChange:(EMConnectionState)aConnectionState
{
    NSString *title = nil;
    switch (aConnectionState) {
        case EMConnectionConnected:
            title = kNormalTitle;
            break;
        case EMConnectionDisconnected:
            title = kDisconnectedTitle;
            break;
    }
    
    self.navigationItem.title = title;
}

#pragma mark - EMChatManagerDelegate

/// 收到好友消息回调方法
- (void)messagesDidReceive:(NSArray<EMMessage *> *)aMessages
{
    // 追加新的会话对象
    for (EMMessage *message in aMessages) {
        if (![self containConversationID:message.conversationId]) {
            // 不包含会话
            [_conversationArrM addObject:[[EMClient sharedClient].chatManager getConversation:message.conversationId type:EMConversationTypeChat createIfNotExist:YES]];
        }
    }
    
    // 统计未读数
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in _conversationArrM) {
        unreadCount += conversation.unreadMessagesCount;
    }
    [self setTabBarItemBageValue:unreadCount];
    
    // 按时间排序 刷新表格
    [_conversationArrM sortUsingFunction:sortConversation context:nil];
    [self.tableView reloadData];
}

#pragma mark - 其他方法

/// 加载所有会话
- (void)loadConversations
{
    // 移除之前的会话对象
    [_conversationArrM removeAllObjects];
    
    // 添加新的会话对象
    NSArray<EMConversation *> *conversationArr = [[EMClient sharedClient].chatManager getAllConversations];
    
    // 统计未读消息
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversationArr) {
        if (conversation.latestMessage != nil) {
            unreadCount += conversation.unreadMessagesCount;
            [_conversationArrM addObject:conversation];
        }
    }
    [self setTabBarItemBageValue:unreadCount];
    
    // 排序并刷新表格
    if (_conversationArrM.count > 0) {
        [_conversationArrM sortUsingFunction:sortConversation context:nil];
        [self.tableView reloadData];
    }
}

/// 判断当前会话数组中是否包含指定的会话
/// @param conversationID 会话id
- (BOOL)containConversationID:(NSString *)conversationID
{
    for (EMConversation *conversation in _conversationArrM) {
        if ([conversation.conversationId isEqualToString:conversationID]) {
            return YES;
        }
    }
    
    return NO;
}

/// 设置tabBar数组角标
/// @param unreadCount 角标数字
- (void)setTabBarItemBageValue:(NSInteger)unreadCount
{
    self.tabBarItem.badgeValue = unreadCount > 0 ? [NSString stringWithFormat:@"%zd",unreadCount] : nil;
}

@end
